package com.tcoiss.webservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tcoiss.webservice.config.wx.config.AccessTokenConfig;
import com.tcoiss.webservice.domain.wx.Article;
import com.tcoiss.webservice.domain.wx.NewsMessage;
import com.tcoiss.webservice.service.IWxApiService;
import com.tcoiss.webservice.utils.WeChatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxApiServiceImpl implements IWxApiService {

    @Autowired
    AccessTokenConfig accessTokenConfig;

    @Autowired
    WeChatUtils weChatUtils;

    @Override
    public int sendWxMessage(Map message) {
        String jobNo = message.get("jobNo").toString();
        //TODO 组装模板数据
        NewsMessage newsMessage = new NewsMessage();
        newsMessage.setTouser(jobNo);//这里传入推送人员工号进行熟客信息推送
        newsMessage.setAgentid(accessTokenConfig.getAgentId());
        newsMessage.setMsgtype("news");
        List<Map<String,Object>> list = (List<Map<String, Object>>) message.get("articles");
        List<Article> articleList = new ArrayList<>();
        for(Map<String,Object> map :list){
            Article article = new Article();
            article.setBtntxt("查看");
            article.setUrl(map.get("url").toString());
            article.setTitle(map.get("title").toString());
            article.setDescription(map.get("description").toString());
            articleList.add(article);
        }
        Map articles = new HashMap();
        articles.put("articles", articleList);
        newsMessage.setNews(articles);
        //发送模板信息
        try {
            weChatUtils.getAccessToken();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String result = weChatUtils.sendMessage(newsMessage);
        JSONObject jsStr = JSONObject.parseObject(result);
        Integer code = Integer.valueOf(jsStr.getString("errcode"));
        return code;
    }
}
